package com.geeker.module.sys.config.controller;

import com.geeker.common.annotation.Log;
import com.geeker.common.annotation.PreAuth;
import com.geeker.common.annotation.RepeatSubmit;
import com.geeker.common.api.CommonResult;
import com.geeker.common.enums.BusinessType;
import com.geeker.common.util.PageUtil;
import com.geeker.module.sys.config.domain.SysConfig;
import com.geeker.module.sys.config.dto.SysConfigDto;
import com.geeker.module.sys.config.service.SysConfigService;
import com.mybatisflex.core.paginate.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Tag(name = "参数配置")
@RequestMapping("/sys/config")
public class SysConfigController {

    @Autowired
    private SysConfigService sysConfigService;

    @Operation(summary = "分页")
    @PostMapping("page")
    public CommonResult<Page<SysConfig>> page(@RequestBody SysConfigDto dto) {
        Page<SysConfig> page = PageUtil.getPage(dto);
        Page<SysConfig> iPage = sysConfigService.page(page);
        return CommonResult.success(iPage);
    }

    @Operation(summary = "详情")
    @PostMapping("detail/{configId}")
    @PreAuth(value = "sys:config:detail")
    public CommonResult<SysConfig> detail(@PathVariable Long configId) {
        return CommonResult.success(sysConfigService.getById(configId));
    }

    @Operation(summary = "根据参数键名查询参数值")
    @PostMapping(value = "/configKey/{configKey}")
    public CommonResult<String> getConfigKey(@PathVariable String configKey) {
        return CommonResult.success(sysConfigService.selectConfigByKey(configKey));
    }

    @RepeatSubmit
    @Operation(summary = "新增")
    @Log(title = "参数管理", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public CommonResult add(@Validated @RequestBody SysConfig config) {
        return CommonResult.success(sysConfigService.add(config));
    }

    @Operation(summary = "编辑")
    @Log(title = "参数管理", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public CommonResult edit(@Validated @RequestBody SysConfig config) {
        return CommonResult.success(sysConfigService.edit(config));
    }

    @RepeatSubmit
    @Operation(summary = "删除参数配置")
    @Log(title = "参数管理", businessType = BusinessType.DELETE)
    @PostMapping("/delete/{configIds}")
    public CommonResult delete(@PathVariable List<Long> configIds) {
        sysConfigService.delete(configIds);
        return CommonResult.success();
    }

    @Operation(summary = "刷新参数缓存")
    @Log(title = "参数管理", businessType = BusinessType.CLEAN)
    @PostMapping("/refreshCache")
    public CommonResult refreshCache() {
        sysConfigService.resetConfigCache();
        return CommonResult.success();
    }
}
